package com.sky.controller.admin;

import com.sky.properties.AliOssProperties;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;

/**
 *
 */
@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口,文件上传")
public class CommonController {
//    @Autowired
//    private AliOssProperties aliOssProperties;
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(@RequestPart MultipartFile file){
        log.info("文件上传：{}", file);
        /**
         * 1. 获取文件的原始文件名 100.jpg
         * 2. 修改原始文件名
         * 3.uuid生成字符串当做文件名
         * 4.调用AliOssUtil上传文件
         * 5.返回上传文件的访问路径
         */
        String originalFilename= file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String suffix =  originalFilename.substring(index);
        String newFileName = UUID.randomUUID() + suffix;

//        AliOssUtil aliOssUtil = new AliOssUtil(aliOssProperties.getEndpoint(),aliOssProperties.getAccessKeyId(),aliOssProperties.getAccessKeySecret(),aliOssProperties.getBucketName());

        try {
            String fillUrl=aliOssUtil.upload(file.getBytes(), newFileName);
            return Result.success(fillUrl);
        }catch (Exception e){
            return Result.error("文件上传失败");
        }
    }
}
